package com.liser.southernstar.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * MD5签名
 */
public class MD5Sign {
    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
    private String jBegin;
    private String jKeyEnd;
    private String jValEnd;
    private String jEnd;

    public MD5Sign(String jBegin, String jKeyEnd, String jValEnd, String jEnd) {
        this.jBegin = jBegin;
        this.jKeyEnd = jKeyEnd;
        this.jValEnd = jValEnd;
        this.jEnd = jEnd;
    }

    private static String byteToHexString(byte b) {
        int n = b;  
        if (n < 0)  {
            n += 256;
        }
        int d1 = n / 16;  
        int d2 = n % 16;  
        return hexDigits[d1] + hexDigits[d2];  
    }

    /**
     * 检查值类型是否支持参与加密
     */
    private boolean isSupportValType(Class<?> valType){
        if(valType == String.class){
            return true;
        }else if(valType == Boolean.class){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 对json签名
     */
    public String sign(String key, JSONObject data) throws NoSuchAlgorithmException {
        try {
            StringBuffer buffer = new StringBuffer();
            // 拼接字符串
            {
                SortedMap<String, Object> sortedMap = new TreeMap<>(data);
                Iterator<SortedMap.Entry<String, Object>> entries = sortedMap.entrySet().iterator();
                SortedMap.Entry<String, Object> entry;
                buffer.append(jBegin).append(key);
                Object valObj;
                while (entries.hasNext()) {
                    entry = entries.next();
                    valObj = entry.getValue();
                    // 不排序null值
                    if(valObj == null){
                        continue;
                    }
                    // 不排序复杂对象
                    if(!isSupportValType(valObj.getClass())){
                        continue;
                    }
                    // 拼接键值
                    buffer.append(entry.getKey()).append(jKeyEnd).append(valObj.toString().toLowerCase()).append(jValEnd);
                }
                buffer.append(jEnd);
            }
            // 加密
            return sign(buffer.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            return null;
        }
    }

    /**
     * 对数据签名
     */
    public static String sign(byte[] data) throws NoSuchAlgorithmException {
        StringBuffer buffer = new StringBuffer();
        // 加密
        byte[] bytes = MessageDigest.getInstance("MD5").digest(data);
        // 转换为字符串
        buffer.setLength(0);
        for (int i = 0, l=bytes.length; i < l; i++) {
            buffer.append(byteToHexString(bytes[i]));
        }
        return buffer.toString();
    }
}
